package ru.rchervot.sanasar.client.event;

import ru.rchervot.sanasar.client.model.ResultsPage;
import ru.rchervot.sanasar.client.model.SearchResultsItem;

import com.google.gwt.event.shared.GwtEvent;

public class EventPageChange<T extends SearchResultsItem> extends GwtEvent<HandlerPageChange<T>> {
	private static Type<HandlerPageChange<?>> TYPE = new Type<HandlerPageChange<?>>();
	
	private ResultsPage<T> page;
	
	private EventPageChange() {}
	
	private EventPageChange(ResultsPage<T> page) {
		this.page = page;
	}
	
	@Override
	protected void dispatch(HandlerPageChange<T> handler) {
		handler.onPageChange(this);
	}

	/**
	 * Gets the type associated with this event.
	 * 
	 * @return returns the handler type
	 */
	public static Type<HandlerPageChange<?>> getType() {
		if (TYPE == null) {
			TYPE = new Type<HandlerPageChange<?>>();
		}
		return TYPE;
	}

	// The instance knows its PlaceChangeEventHandler is of type T, but the TYPE
	// field itself does not, so we have to do an unsafe cast here.
	@SuppressWarnings("unchecked")
	@Override
	public Type<HandlerPageChange<T>> getAssociatedType() {
		return (Type) TYPE;
	}

	public ResultsPage<T> getPage() {
		return page;
	}
	
	public boolean isStartPage() {
		return page == null;
	}
	
	public static <T extends SearchResultsItem> EventPageChange<T> 
	build(ResultsPage<T> page) {
		return new EventPageChange<T>(page);
	}
	
	public static <T extends SearchResultsItem> EventPageChange<T> 
	buildStartPage() {
		return new EventPageChange<T>(null);
	}
}
